﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;

namespace CSI300Cons.CapitalDownloader
{
    public class Log
    {
        private static bool LogToFile = (ConfigurationManager.AppSettings["LogToFile"] == "1");

        private static object obj = new object();

        private static int Debug = 0;
        private static string ServiceDirectory;

        public Log(int debug, string dir)
        {
            Debug = debug;
            ServiceDirectory = dir;
        }

        public static string GetDateTime()
        {
            return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        }

        public void Output(string msg)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.WriteLine(GetDateTime() + msg);
                }
            }

        }

        public void Output(string msg, bool log)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.WriteLine(GetDateTime() + msg);
                }

                if (log)
                {
                    if (LogToFile)
                    {
                        this.WriteToFile(ServiceDirectory + @"\Log\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
                    }
                }
            }

        }

        public void Output(string msg, ConsoleColor color)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.ForegroundColor = color;
                    Console.WriteLine(GetDateTime() + msg);
                    Console.ResetColor();
                }
            }
        }

        public void Output(string msg, ConsoleColor color, bool log)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.ForegroundColor = color;
                    Console.WriteLine(GetDateTime() + msg);
                    Console.ResetColor();
                }

                if (log)
                {
                    if (LogToFile)
                    {
                        this.WriteToFile(ServiceDirectory + @"\Log\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
                    }
                }
            }
        }

        private void WriteToFile(string filename, string content)
        {
            using (StreamWriter sw = new StreamWriter(filename, true))
            {
                sw.WriteLine(content);
                sw.Close();
            }
        }
    }
}
